//
//  KSRssParser.m
//  KSLib
//
//  Created by User on 9/24/11.
//  Copyright 2011 __MyCompanyName__. All rights reserved.
//

#import "KSRssParser.h"
#import "KSRssItem.h"


@implementation KSRssParser

@synthesize rssCol;

-(id) loadRssByURL:(NSString *)urlString
{
    
    if(parser)
    {
        [parser release];
    }
    
	rssCol			= [[NSMutableArray alloc] init];
	NSURL *url		= [NSURL URLWithString:urlString];
	NSData	*data   = [[NSData alloc] initWithContentsOfURL:url];
    
	parser			= [[NSXMLParser alloc] initWithData:data];
	parser.delegate = self;
    
    [parser setShouldProcessNamespaces:YES];
	[parser setShouldReportNamespacePrefixes:YES];
	[parser setShouldResolveExternalEntities:NO];
    
	[parser parse];
	return self;
}

- (void) parser:(NSXMLParser *)parser didStartElement:(NSString *)elementname namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName attributes:(NSDictionary *)attributeDict
{
	if ([elementname isEqualToString:@"item"]) 
	{
		currentRssItem = [KSRssItem alloc];
	}
}


- (void) parser:(NSXMLParser *)parser didEndElement:(NSString *)elementname namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName
{
	if([elementname isEqualToString:@"title"]){
		currentRssItem.title = currentNodeContent;
        
	}else if([elementname isEqualToString:@"description"]){
		currentRssItem.description = currentNodeContent;
        
	}else if([elementname isEqualToString:@"link"]){
		currentRssItem.linkUrl = currentNodeContent;
        
	}else if([elementname isEqualToString:@"guid"]){
		currentRssItem.guidUrl = currentNodeContent;
        
	}else if([elementname isEqualToString:@"pubDate"]){
		NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
		[formatter setDateFormat:@"yyyy-MM-dd'T'HH:mm:ss'Z'"];
		currentRssItem.pubDate = [formatter dateFromString:currentNodeContent];
		[formatter release];
        
	}else if([elementname isEqualToString:@"item"]){
		[rssCol addObject:currentRssItem];
        currentRssItem = nil;
		[currentRssItem release];
		currentNodeContent = nil;
		[currentNodeContent release];

	}
}

- (void) parser:(NSXMLParser *)parser foundCharacters:(NSString *)string
{
	currentNodeContent = (NSMutableString *) [string stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];
}

- (void) dealloc
{
	[parser release];
	[super dealloc];
}


@end
